package com.adan.content.service.impl;

import com.adan.content.mapper.CourseCategoryMapper;
import com.adan.content.model.dto.CourseCategoryTreeDto;
import com.adan.content.model.po.CourseCategory;
import com.adan.content.service.CourseCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author adan
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Resource
    private CourseCategoryMapper courseCategoryMapper;


    @Override
     public List<CourseCategoryTreeDto> queryTreeNodes() {
        //获取全部课程分类信息
        /* List<CourseCategory> courseCategoryList = this.list();
        List<CourseCategoryTreeDto> list = new ArrayList<>();
        courseCategoryList.forEach(item -> {
            CourseCategoryTreeDto categoryTreeDto = new CourseCategoryTreeDto();
            BeanUtils.copyProperties(item, categoryTreeDto);
            list.add(categoryTreeDto);
        }); */
        //获取全部课程分类信息
        List<CourseCategoryTreeDto> list = courseCategoryMapper.selectTreeNodes();

        // 递归组装多级分类的树形结构
        List<CourseCategoryTreeDto> courseCategoryNodes = list.stream()
                // 筛选出一级分类
                .filter(item -> item.getParentid().equals("1"))
                .peek(item -> item.setChildrenTreeNodes(getChildren(item, list))).collect(Collectors.toList());


        return courseCategoryNodes;
    }

    /**
     * 获取父节点的子节点信息
     * @param parent 父节点
     * @param list 所有节点信息
     * @return 子节点信息
     */
    private List<CourseCategoryTreeDto> getChildren(CourseCategoryTreeDto parent, List<CourseCategoryTreeDto> list) {
        List<CourseCategoryTreeDto> childrenNodes = list.stream()
                .filter(children -> children.getParentid().equals(parent.getId())).collect(Collectors.toList());
        return childrenNodes;
    }


}
